<template>
  <view class="container">
    <button @click="chooseVideo">选择视频</button>
    <video id="myVideo" v-if="videoSrc" :src="videoSrc" controls style="width: 100%;"></video>
    <video id="hiddenVideo" style="display:none;"></video>
    <canvas canvas-id="firstFrameCanvas" style="width: 100%; height: auto; display: none;"></canvas>
    <image v-if="firstFrame" :src="firstFrame" mode="aspectFit" style="width: 100%; margin-top: 20px;"></image>
  </view>
</template>

<script>
export default {
  data() {
    return {
      videoSrc: '',
      firstFrame: ''
    };
  },
  methods: {
    chooseVideo() {
      uni.chooseVideo({
        success: (res) => {
          console.log('视频选择成功', res);
          this.videoSrc = res.tempFilePath;
          this.getFirstFrame(res.tempFilePath);
        },
        fail: (err) => {
          console.error('选择视频失败', err);
        }
      });
    },
    getFirstFrame(videoPath) {
      const hiddenVideo = document.getElementById('hiddenVideo');
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      hiddenVideo.src = videoPath;
      
      hiddenVideo.addEventListener('loadeddata', () => {
        console.log('视频已加载');
        hiddenVideo.currentTime = 1; // 跳转到视频的第0秒
      });

      hiddenVideo.addEventListener('seeked', () => {
        console.log('视频跳转到第0秒');
        canvas.width = hiddenVideo.videoWidth;
        canvas.height = hiddenVideo.videoHeight;
        ctx.drawImage(hiddenVideo, 0, 0, canvas.width, canvas.height);
        console.log('canvas绘制完成');

        // 将canvas转换为图片
        canvas.toBlob((blob) => {
          const url = URL.createObjectURL(blob);
          this.firstFrame = url;
          console.log('截取第一帧成功', url);
        });
      });

      hiddenVideo.addEventListener('error', (err) => {
        console.error('视频加载错误', err);
      });
    }
  }
};
</script>

<style>
.container {
  padding: 20px;
}
</style>
